package com.hk.blog.service.impl;

import com.hk.blog.domain.RolePermission;
import com.hk.blog.repository.jpa.RolePermissionRepository;
import com.hk.blog.service.RolePermissionService;
import com.hk.commons.util.CollectionUtils;
import com.hk.core.data.jpa.repository.BaseJpaRepository;
import com.hk.core.service.jpa.impl.JpaServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author Kevin
 * @date 2022-06-26 16:39
 */
@Service
@RequiredArgsConstructor
public class RolePermissionServiceImpl extends JpaServiceImpl<RolePermission, Long>
        implements RolePermissionService {

    private final RolePermissionRepository rolePermissionRepository;

    @Override
    protected BaseJpaRepository<RolePermission, Long> getBaseRepository() {
        return rolePermissionRepository;
    }

    @Override
    public Set<Long> findPermissionIdsByRoleId(Long roleId) {
        return Objects.isNull(roleId) ? Collections.emptySet()
                : rolePermissionRepository.findPermissionIdsByRoleId(roleId);
    }

    @Override
    public Set<Long> findPermissionIdsByRoleIds(Set<Long> roleIds) {
        return CollectionUtils.isEmpty(roleIds) ? Collections.emptySet() :
                roleIds.size() == 1 ? findPermissionIdsByRoleId(roleIds.iterator().next())
                        : rolePermissionRepository.findPermissionIdsByRoleIds(roleIds);
    }

    @Override
    public Set<Long> findRoleIdsByPermissionIds(Set<Long> permissionIds) {
        return CollectionUtils.isEmpty(permissionIds) ? Collections.emptySet() :
                permissionIds.size() == 1 ? rolePermissionRepository.findRoleIdsByPermissionId(permissionIds.iterator().next())
                        : rolePermissionRepository.findRoleIdsByPermissionIds(permissionIds);
    }

    @Override
    @Transactional
    public void updateRolePerms(Long roleId, Set<Long> permissionIds) {
        rolePermissionRepository.deleteByRoleId(roleId);
        if (CollectionUtils.isNotEmpty(permissionIds)) {
            var list = new ArrayList<RolePermission>(permissionIds.size());
            for (var item : permissionIds) {
                list.add(new RolePermission().setPermissionId(item).setRoleId(roleId));
            }
            rolePermissionRepository.saveAll(list);
        }
    }

}
